package com.ybwh.springboot2.minio.controller;

import com.ybwh.springboot2.common.RespData;
import com.ybwh.springboot2.filetree.utils.FileTreeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author saytime
 * @since 2018-12-06
 */
@Api(tags = "标准上传下载步骤")
@Controller
@RequestMapping("/minio/standard")
public class MinioStandardController {


    @ApiOperation(value = "下载文件", notes = "")
    @RequestMapping(value = "/down", method = RequestMethod.GET)
    public void down(@ApiParam(value = "文件ID", required = true) @RequestParam("id") Long id, HttpServletResponse response) throws IOException {
        // 这里 FileInputStream 应该根据文件ID去文件服务器取,FileInputStream需要自己关闭
        try (FileInputStream fis = new FileInputStream("D:/33.txt")){
            FileTreeUtils.downFile(fis, "345.txt", response,false);
        }
    }


    @ApiOperation(value = "上传文件", notes = "")
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public RespData upload(@ApiParam(value = "上传文件", required = true) @RequestParam("file") MultipartFile file)
            throws IllegalStateException, IOException {

        // 50M
        if (file.getSize() > 50 * FileTreeUtils.MB) {
            throw new MaxUploadSizeExceededException(50 * FileTreeUtils.MB);
        }


        file.transferTo(new File("D:/tmp/" + file.getOriginalFilename()));


        return RespData.successResp(null);

    }


}
